import { createMap } from 'common'
import $ from 'jquery'

$('.box').on('submit', function (e) {
  $.ajax({
    method: 'post',
    url: '/api/map/add',
    processData: false,
    data: $(e.target).serialize(),
    success() {
      e.target.reset()
    }
  })
})

async function bootstrap() {
  const map = await createMap(document.getElementById('map'))

  let index = 0

  const $box = $('form.box')

  map.on('click', function (e) {
    index++

    const lng = e.lnglat.getLng()
    const lat = e.lnglat.getLat()

    const title = `标记-${index}`
    const marker = new AMap.Marker({
      position: new AMap.LngLat(lng, lat),
      title
    })

    $box.append(`
      <input type="hidden" name="lnglat[]" value=${[lng, lat, title].join(',')}>
    `)

    marker.setLabel({
      direction: 'bottom',
      offset: new AMap.Pixel(0, 10),
      content: `<div style='padding: 1px 5px;'>${title}</div>`
    })

    map.add(marker)
  })

  map.on('mapmove', function () {
    console.log('center', map.getCenter())
  })
}

bootstrap()
